import React, {Component} from 'react';
import {Select, DatePicker, Form, Row, Col, Input, Button, Popover, Icon} from 'antd';
import moment from 'moment';
import PropTypes from 'prop-types';
import {alilogStore} from '../../fetch/fetchApi';
import {systemLogsForSdk} from "../../utils/aliconfig";
import dateFormats from "./date-format-constant";

moment.locale('zh-cn');

const Option = Select.Option;
const FormItem = Form.Item;

const popContent = (
  <div>

    <p>查询：</p>
    <p>1. 全文查询： error</p>
    <p>2. 指定字段查询：Latency>5000 and Method:Get* not Status:200</p>
    <p>3. 短语（指定引号）："http error"</p>
    <p>分析：</p>
    <p>1. 带查询条件：* | $analytics</p>
    <p>2. 无查询条件：$search | $analytics</p>

    <p>查询语法： <a target='_blank'
                href='https://help.aliyun.com/document_detail/29060.html?spm=5176.doc29029.2.3.4jvt6H'>查询语法</a></p>

  </div>
);

/**
 *  阿里云日志查询
 */
class AliLogQueryFilter extends Component {

  state = {
    listLogstore: [],
    selectedLogstore: ''
  }

  componentDidMount() {
    // To disabled submit button at the beginning.
    this.props.form.validateFields();
  }

  getSystemLogSelect = () => {
    return (
      systemLogsForSdk.map((systemLog, i) => {
        return <Option value={systemLog.logger} key={systemLog.logger}>{systemLog.application}</Option>
      })
    )
  }

  async listLogstore (project) {
    try {
      const resData = await alilogStore({
        project: project
      });
      return resData.data;
    } catch (e) {
      console.log(e);
    }
  }

  handleProjectChange = (val) => {
    this.setState({listLogstore: [], selectedLogstore: ''});
    if (val) {
      this.listLogstore(val).then((result) => {
        if (result && result.code === '200' && result.data.length > 0) {
          this.setState({
            listLogstore: result.data,
            selectedLogstore: result.data[0]
          });

          this.props.form.setFieldsValue({
            logstorename: this.state.selectedLogstore
          });
        }
      })
    } else {
      this.props.form.setFieldsValue({
        logstorename: this.state.selectedLogstore
      });
    }
  }

  hasErrors = (fieldsError) => {
    return Object.keys(fieldsError).some(field => fieldsError[field]);
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const {form, onFilterChange} = this.props;
        const {getFieldsValue} = form;
        let fieldsValue = getFieldsValue();
        //刷新列表
        const params = {
          ...fieldsValue,
          lastQueryTime: moment().format('x'),
          project: fieldsValue["project"],
          logstorename: fieldsValue["logstorename"],
          startDate: fieldsValue["startDate"].format(dateFormats.DATE_FORMAT_SEC_WITH_HYPHEN),
          endDate: fieldsValue["endDate"].format(dateFormats.DATE_FORMAT_SEC_WITH_HYPHEN),
          query: fieldsValue["query"]
        };
        onFilterChange(params);
      }
    });
  }

  render() {
    const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form;
    const listlogstorename = this.state.listLogstore.map(logstore => <Option key={logstore}
                                                                             value={logstore}>{logstore}</Option>);

    // Only show error after a field is touched.
    const projectError = isFieldTouched('project') && getFieldError('project');
    const logstorenameError = isFieldTouched('logstorename') && getFieldError('logstorename');
    return (
      <Form layout="inline" onSubmit={this.handleSubmit}>
        <Row gutter={24}>
          <Col>
            <FormItem validateStatus={projectError ? 'error' : ''} help={projectError || ''}>
              {
                getFieldDecorator('project', {
                  rules: [{required: true, message: '请选择项目!'}]
                })(<Select placeholder="项目" style={{width: 100}}
                           onChange={this.handleProjectChange}>
                  {
                    this.getSystemLogSelect()
                  }
                </Select>)
              }
            </FormItem>
            <FormItem validateStatus={logstorenameError ? 'error' : ''} help={logstorenameError || ''}>
              {
                getFieldDecorator('logstorename', {
                  rules: [{required: true, message: '请选择日志级别!'}]
                })(<Select placeholder="日志级别"
                           style={{width: 100}}>
                  {
                    listlogstorename
                  }
                </Select>)
              }
            </FormItem>
            <FormItem>
              {
                getFieldDecorator('startDate', {
                  rules: [{required: true, message: '请选择起始时间!'}],
                  initialValue: moment()
                })(<DatePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder="起始时间"
                               allowClear={false}/>)
              }
            </FormItem>
            <FormItem>
              {
                getFieldDecorator('endDate', {
                  rules: [{required: true, message: '请选择结束时间!'}],
                  initialValue: moment()
                })(<DatePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder="结束时间"
                               allowClear={false}/>)
              }
            </FormItem>
            <FormItem>
              {
                getFieldDecorator('query', {
                  rules: []
                })(<Input type="text" addonAfter={
                  <Popover placement="bottom" content={popContent} title='' trigger='hover'><Icon
                    type="question-circle-o"/></Popover>
                }  placeholder="输入桩编号或关键字"/>)
              }

            </FormItem>
            <FormItem>
              <Button type="primary" htmlType="submit" icon="search"
                      disabled={this.hasErrors(getFieldsError())}> 搜索 </Button>
            </FormItem>
          </Col>
        </Row>
      </Form>
    );
  }

}

AliLogQueryFilter.propTypes = {
  onFilterChange: PropTypes.func,
  form: PropTypes.object
}

//经过 Form.create 包装的组件将会自带 this.props.form 属性，this.props.form
export default Form.create()(AliLogQueryFilter);